package com.fenghuaxz.rpcframework.model;

import com.fenghuaxz.rpcframework.OnCallbackListener;
import io.netty.channel.Channel;
import java.lang.reflect.Method;

public class UnsyncCallback implements MsgCallback{
    private Method method;
    private OnCallbackListener listener;

    public UnsyncCallback(Method method, OnCallbackListener listener) {
        this.method=method;
        this.listener=listener;
    }

    @Override
    public Object await() throws Exception {
        return getReturnObject(method.getReturnType());
    }

    @Override
    public void handler(MsgResponse response, Channel channel) throws Exception {
        if (listener!=null){
            String error = response.getException();
            if (error!=null)
                listener.onError(error);
            else
                listener.onCallback(method,channel,response.getResult());
        }
    }

    private final Object getReturnObject(Class<?> type){
        return boolean.class.isAssignableFrom(type) ? false : type.isPrimitive() ? 0 : null;
    }
}
